﻿#include "ThreadTaskManager.h"
#include <QDebug>
#include "ThreadTask.h"
#include "ThreadControl.h"
#include "BaseWidget/IWidgetSignal.h"

namespace BaseWidget
{
    ThreadTaskManager* ThreadTaskManager::m_instance = nullptr;

    ThreadTaskManager* ThreadTaskManager::getInstance()
    {
        if (m_instance == nullptr)
        {
            m_instance = new ThreadTaskManager;
        }
        return m_instance;
    }

    ThreadTaskManager::ThreadTaskManager()
    {
        auto _widgetSignal = IWidgetSignalInstance;
        connect(_widgetSignal, &BaseWidget::IWidgetSignal::signal_appendThreadTask, this, &ThreadTaskManager::slot_appendThreadTask);
    }

    void ThreadTaskManager::clearThreadList()
    {
        foreach(auto & iter, m_threadContolList)
        {
            if (iter)
            {
                emit iter->signal_threadStop();
            }
        }

        m_threadContolList.clear();
    }

    void ThreadTaskManager::slot_appendThread(ThreadControl* thread)
    {
        if (!m_threadContolList.contains(thread->getUUID()))
        {
            m_threadContolList.insert(thread->getUUID(), thread);
        }
    }

    void ThreadTaskManager::slot_removeThread(QString uuid)
    {
        m_threadContolList.remove(uuid);
    }

    void ThreadTaskManager::slot_appendThreadTask(ThreadTask* threadTask)
    {
        auto _thread = new BaseWidget::ThreadControl(threadTask);
        connect(_thread, &ThreadControl::signal_removeThread, this, &ThreadTaskManager::slot_removeThread);
        slot_appendThread(_thread);
    }

}
